package com.hepinghospital.user.ui.activity.prescription;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.shape.layout.ShapeLinearLayout;
import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.AliPayFeeAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.eventbus.AlipaySuccessEvent;
import com.hepinghospital.user.eventbus.WebSocketWrapper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.response.MedicineListResponse;
import com.rest.response.PrescriptionResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilString;

/**
 * Description
 * Created by lbj on 2023/1/11 8:55
 */

public class AtyAliPayResult extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.iv_alipay_status)
    ImageView ivAlipayStatus;
    @BindView(R.id.tv_alipay_status)
    TextView tvAlipayStatus;
    @BindView(R.id.sl_alipay_ing)
    ShapeLinearLayout slAlipayIng;
    @BindView(R.id.rv_fee_detail)
    RecyclerView rvFeeDetail;
    @BindView(R.id.tv_fee_total)
    TextView tvFeeTotal;
    @BindView(R.id.tv_medical_insurance)
    TextView tvMedicalInsurance;
    @BindView(R.id.tv_fee_other)
    TextView tvFeeOther;
    @BindView(R.id.tv_cash_pay)
    TextView tvCashPay;
    @BindView(R.id.sl_alipay_success)
    ShapeLinearLayout slAlipaySuccess;
    @BindView(R.id.tv_back)
    TextView tvBack;
    MedicineListResponse.MedicineOrder order;
    List<PrescriptionResponse.Prescription> listFee = new ArrayList<>();
    AliPayFeeAdapter aliPayFeeAdapter;

    private CountDownTimer timer;
    private String orderId, query, prescriptionAmount, receiveId, getType;

    private boolean isAlipaySucess;


    @Override
    protected int getLayoutResource() {
        return R.layout.aty_alipay_result;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        tvTitle.setText("支付结果");
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvFeeDetail.setLayoutManager(manager);
        aliPayFeeAdapter = new AliPayFeeAdapter(this, listFee);
        rvFeeDetail.setAdapter(aliPayFeeAdapter);
        btn_back.setOnClickListener(v -> onBackPressed());
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        orderId = getIntent().getStringExtra("orderId");
        receiveId = getIntent().getStringExtra("receiveId");
        getType = getIntent().getStringExtra("getType");

        if (!UtilString.isEmpty(orderId)) {
            query = "orderId=" + orderId + "&receiveId=" + receiveId + "&getType=" + getType + "&token=" + RestClient.getInstance().token;
            timer = new CountDownTimer(1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {
                    //倒计时为0时执行此方法
                    startAliPay(mContext, "2021004139621385", "", query);
                }
            };
            timer.start();

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //从小程序返回app，调用处方详情接口,需要根据消息机制再查询一次，消息机制后台还没有给
        getMedicineOrderDetail(orderId);
    }

    private void getMedicineOrderDetail(String orderId) {
        showLoadingDialog(mContext);
        RestProxy.getInstance().getMedicineOrderDetail(orderId, new Observer<PrescriptionResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(PrescriptionResponse prescriptionResponse) {
                dismissLoadingDialog();
                //根据处方支付状态，来展示不同界面（支付中，支付完成，支付失败）
                //status ：0未审核，1待支付2驳回3待发货4待签收5已完成6待取药7已取消8申请退药9待寄出10已寄出11已退药
                if ("1".equals(prescriptionResponse.status)) {
                    slAlipayIng.setVisibility(View.VISIBLE);
                } else if ("3".equals(prescriptionResponse.status) || "6".equals(prescriptionResponse.status)) {
                    //待发货，支付成功，不过需要再和后台确定
                    slAlipayIng.setVisibility(View.GONE);
                    ivAlipayStatus.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.succeed));
                    tvAlipayStatus.setText("支付成功");
                    slAlipaySuccess.setVisibility(View.VISIBLE);
                    isAlipaySucess = true;
                } else if ("2".equals(prescriptionResponse.status)) {
                    ivAlipayStatus.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.failed));
                    tvAlipayStatus.setText("支付失败");
                }
                prescriptionAmount = prescriptionResponse.prescriptionAmount;
                tvFeeTotal.setText(prescriptionAmount);
                tvMedicalInsurance.setText(prescriptionResponse.recPayAmout);
                tvCashPay.setText(prescriptionResponse.totalAmount);
                tvFeeOther.setText(prescriptionResponse.discountAmout);

                listFee.clear();
                listFee.addAll(prescriptionResponse.westernNameDtoList);
                aliPayFeeAdapter.notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        EventBus.getDefault().unregister(this);
    }


    /**
     * 支付宝小程序
     *
     * @param context 上下文处理
     * @param appId   小程序appId
     * @param page    小程序跳转的页面。如果不设置，默认为跳转至首页。例如：pages/user/user
     * @param query   启动参数，内容按照格式为参数名=参数值&参数名=参数值…之后encode，例如：client_type=2
     */
    public static void startAliPay(Context context, String appId, String page, String query) {
        try {
            StringBuilder sb = new StringBuilder("alipays://platformapi/startapp?");
            sb.append("appId=").append(appId).append("&");
            sb.append("page=").append(page).append("&");
            String link = URLEncoder.encode(query, "UTF-8");
            sb.append("query=").append(link);
            Uri uri = Uri.parse(sb.toString());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    @OnClick(R.id.tv_back)
    public void onViewClicked() {
        startActivity(new Intent(mContext, MyMedicineActivity.class));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocketWrapper webSocket) {
        if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_114) {
            getMedicineOrderDetail(orderId);
        } else if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_115) {
            ivAlipayStatus.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.failed));
            tvAlipayStatus.setText("支付失败");
        }
    }

    @Override
    public void onBackPressed() {
        if (isAlipaySucess) {
            LogUtil.e("支付宝医保支付成功");
            EventBus.getDefault().postSticky(new AlipaySuccessEvent());
        }
        super.onBackPressed();
    }
}
